//
//  NetService.swift
//  kano
//
//  Created by Frank on 2024/9/6.
//

import Foundation
import UIKit

let badNetWorking = "Your network is not working!"

class NetService {
    
    static func ka_serviceConfig() {
        loginProvider.request(.getConfig) { result in
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    guard let responseString = String(data: response.data, encoding: .utf8) else {return}
                    guard let data = responseString.data(using: .utf8) else {return}
                    do {
                        let responseObject = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
                        if let arrayResponse = responseObject as? Dictionary<String, String> {
                            if arrayResponse.count > 0 {
                                let newValue = arrayResponse["d"]
                                UserDefaults.standard.setValue(newValue, forKey: "kConfig")
                            }
                        }
                        //                        if let arrayResponse = responseObject as? [Any] {
                        //                            if let first = arrayResponse.first as? Dictionary<String, String> {
                        //                                let newValue = first["realm"]
                        //                                UserDefaults.standard.setValue(newValue, forKey: "kConfig")
                        //                            }
                        //                        }
                    } catch {return}
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
        
        let paraDic = [
            "userGid":KAUserManager.shared.user.userGid,
            "userToken": KAUserManager.shared.user.userToken,
            "cliendId": UIDevice.ka_UUID,
            "zuid" : UIDevice.ka_UUID
        ]
        loginProvider.request(.autoLogin(paraDic)) { result in
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAUser>.handleResponseData(response.data) { isSuccess, message, response in
                        if !isSuccess {
                            KAUserManager.shared.userLogout()
                        } else {
                            //other operation
                            KAReport.ka_reportWith(type: .device)
                            //登录成功
                            KAAFTool.logEvent(event: "SKP_Success_Login")
                        }
                    }
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    
    static func ka_loginWith(mobile: String, password: String, codeToken: String, operationType: KAOperation, verifyCode: String, verifyToken: String,captchaCode: String, captchaId: String, secondLogin: Int, handler:@escaping NetHandler<KAUser>) {
        let mobile = KAUserManager.shared.user.mobile
        var paraDic: [String : Any] = [
            "mobile":mobile,
            "backMobile":mobile,
            "password":password,
            "codeToken":codeToken,
            "zuid":UIDevice.ka_UUID,
            "cliendId":UIDevice.ka_UUID,
            "loginType": "0",
            "secondLogin": secondLogin,
            "firstLogin": KAUserManager.shared.appIsFirstLaunched(mobile),
            "operationType": 0,
            "authorizationCode": operationType.rawValue,
            "invitionCode": verifyCode,
            "accessToken": 1,
            "userGoogleGid":"",
            "gmail": "",
        ]
        if operationType == .Register {
            paraDic.updateValue(1, forKey: "needCheckVerify")
            paraDic.updateValue(verifyCode, forKey: "verifyCode")
            paraDic.updateValue(verifyToken, forKey: "verifyToken")
        }
        if !captchaCode.isEmpty {
            paraDic.updateValue(1, forKey: "needCheckImgCode")
            paraDic.updateValue(captchaCode, forKey: "captchaCode")
            paraDic.updateValue(captchaId, forKey: "captchaId")
        }
        UIViewController.ka_current().view.showLoading()
        loginProvider.request(.login(paraDic)) { result in
            UIViewController.ka_current().view.hideLoading()
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAUser>.handleResponseData(response.data) { isSuccess, message, response in
                        if isSuccess {
                            guard let user = response?.content else { return }
                            let defaultUser = KAUserManager.shared.user
                            var newUser = defaultUser.merge(with: user)
                            newUser.mobile = KAUserManager.shared.user.mobile
                            KAUserManager.shared.user = newUser
                            KAUserManager.shared.userLogin(with: newUser.mobile)
                            
                            KAReport.ka_reportWith(type: .device)
                            KAReport.ka_reportWith(type: .loaction)
                            //登录成功
                            KAAFTool.logEvent(event: "SKP_Success_Login")
                            
                            if KALocationManager.shared.status == .authorizedAlways || KALocationManager.shared.status == .authorizedWhenInUse {
                                KAReport.ka_reportWith(type: .permissionLoc, data: ["permit" : true])
                            } else {
                                KAReport.ka_reportWith(type: .permissionLoc, data: ["permit" : false])
                            }

                            handler(isSuccess,message, response)
                        } else {
                            handler(isSuccess,message, response)
                        }
                    }
                }else {
                    handler(false, badNetWorking, nil)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    
    static func ka_checkMobileWith(mobile: String, handler:@escaping NetHandler<KAUser>) {
        let paraDic = [
            "mobile":KAEncrypt.ka_encrypt(mobile), "zuid":UIDevice.ka_UUID, "backMobile":mobile
        ]
        UIViewController.ka_current().view.showLoading()
        loginProvider.request(.checkMobile(paraDic)) { result in
            UIViewController.ka_current().view.hideLoading()
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAUser>.handleResponseData(response.data) { isSuccess, message, response in
                        handler(isSuccess,message, response)
                    }
                }else {
                    handler(false, badNetWorking, nil)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    //codeToken校验手机号接口返回；captchaCode图片验证码接口返回；
    static func ka_sentCode(withType codeType: String, codeToken: String, operationType:KAOperation, captchaCode: String = "", newMobile: String = "", handler:@escaping NetHandler<KAContent>) {
        let phoneNM = newMobile.isEmpty ? KAUserManager.shared.user.mobile : newMobile
        let paramDic: [String: Any] = [
            "mobile": phoneNM,
            "codeType": codeType,
            "codeToken": codeToken,
            "operationType": operationType.rawValue,
            "verifyPicCode": captchaCode,
            "pictureId": "",
            "userIP": "",
            "sliderVerifyCodeStatus": "",
            "geetestChallenge": "",
            "geetestValidate": "",
            "geetestSeccode": "",
            "extChannel": "",
            "userGid": "",
            "backMobile": "",
            "lightipv4": "",
            "pictureStatus": ""
        ]
        UIViewController.ka_current().view.showLoading()
        loginProvider.request(.sendCode(paramDic)) { result in
            UIViewController.ka_current().view.hideLoading()
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAContent>.handleResponseData(response.data) { isSuccess, message, response in
                        handler(isSuccess,message, response)
                    }
                }else {
                    handler(false, badNetWorking, nil)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
        
    }
    
    static func ka_reportWith(param: Dictionary<String, Any>? = nil, handler: NetHandler<KAContent>? = nil) {
        var array: [[String: Any]] = []
        array.append(param!)
        reportProvider.request(.report(array)) { result in
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAContent>.handleResponseData(response.data) { isSuccess, message, response in
                        //                        handler(isSuccess,message, response)
                        print("Report Success: \(param!["mid"]!)")
                    }
                }else {
                    //                    handler(false, badNetWorking, nil)
                    print("Report Fail: \(param!["mid"]!)")
                    ka_reportWith(param: param, handler: nil)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    
    static func ka_reportSubChannel(handler: NetHandler<KAContent>? = nil) {
        let paraDic = [
            "userGid":KAUserManager.shared.user.userGid,
            "reqSubChannel": KAAFTool.channel()
        ]
        print("-----: \(KAAFTool.channel())")
        reportProvider.request(.subchannel(paraDic)) { result in
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAContent>.handleResponseData(response.data) { isSuccess, message, response in
                        //                        handler(isSuccess,message, response)
                        print("Report Success: SubChannel")
                    }
                }else {
                    //                    handler(false, badNetWorking, nil)
                    print("Report Fail: SubChannel")
                    ka_reportSubChannel()
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    
    
    static func ka_requestHomeInfo(handler:@escaping NetHandler<KAHomeInfo>) {
        let paraDic: [String : Any] = [
            "userGid": KAUserManager.shared.user.userGid,
            "newVersions" : 0
        ]
        loginProvider.request(.homeInfo(paraDic)) { result in
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAHomeInfo>.handleResponseData(response.data) { isSuccess, message, response in
                        if isSuccess {
                            guard let content = response?.content else { return }
                            if (content.firstAuthFlag == 1) {
                                //用户首次授信成功
                                KAAFTool.logEvent(event: "SKP_Firstsuccessfulcredit_extension")
                            }
                            if (content.firstGetQuotaFlag == 1) {
                                //首次获取额度成功
                                KAAFTool.logEvent(event: "SKP_Successfullyobtained_creditfirst")
                            }
                            //存本地，方便在其他地方使用
                            KADBDBManager.ka_saveInDocument(object: content.kj.JSONString(), fileName: "homeInfo")
                        }
                        handler(isSuccess,message, response)
                    }
                }else {
                    handler(false, badNetWorking, nil)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    
    class func ka_requestHomeStatus(handler:@escaping NetHandler<KAAuditState>) {
        let paramDic: [String : Any] = [
            "userGid": KAUserManager.shared.user.userGid,
        ]
        loginProvider.request(.creditStatus(paramDic)) { result in
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAAuditState>.handleResponseData(response.data) { isSuccess, message, response in
                        if isSuccess {
                            guard let content = response?.content else { return }
                            KADBDBManager.ka_saveInDocument(object: content.kj.JSONString(), fileName: "auditStatus")
                        }
                        handler(isSuccess,message, response)
                    }
                }else {
                    handler(false, badNetWorking, nil)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    //筛选可用的产品
    class func getActiveProduct(content: KAHomeInfo) -> KAProductInfo? {
        guard content.productInfosList!.count > 0 else {return nil}
        
        let list:[KAProductInfo] = content.productInfosList!
        var normalLoan: KAProductInfo?
        var largeLoan: KAProductInfo?
        _ = list.map {
            // 14days小额，蝌蚪贷也是小额类型
            if ($0.productType == 1) {
                normalLoan = $0;
            }
            // Large installment
            if ($0.productType == 2) {
                largeLoan = $0;
            }
        }
        //有小额没大额，显示小额
        if (normalLoan != nil && largeLoan == nil){
            return normalLoan
        }
        //有大额没小额，显示大额
        if (normalLoan == nil && largeLoan != nil){
            return largeLoan
        }
        //大小额都有，
        if (normalLoan != nil && largeLoan != nil) {
            //大小额最大授信额度
            let largeAmount = largeLoan!.creditLine;
            let smallAmount = normalLoan!.creditLine;
            let maxCreditLine = max(largeAmount, smallAmount);
            //大小额授信额度都大于0
            if (smallAmount > 0 && largeAmount > 0) {
                // borrowingLoanType 0:无在借订单  1:有短贷  2:有大额分期订单
                if (content.borrowingLoanType == 0) {
                    let smallBorrowAmount = normalLoan!.canBorrowAmount;
                    let largeBorrowAmount = largeLoan!.canBorrowAmount;
                    largeLoan!.creditLine = maxCreditLine;
                    largeLoan!.canBorrowAmount = max(largeBorrowAmount, smallBorrowAmount);
                    return largeLoan
                }
                if (content.borrowingLoanType == 2) {
                    largeLoan!.creditLine = maxCreditLine;
                    return largeLoan
                }
                if (content.borrowingLoanType == 1) {
                    normalLoan!.creditLine = maxCreditLine;
                    return normalLoan
                }
            }
            if (largeAmount > 0) {
                return largeLoan
            }
            if (smallAmount > 0) {
                return normalLoan
            }
            //大小额授信额度都为0
            if (normalLoan!.creditLine == 0 && largeLoan!.creditLine == 0) {
                return largeLoan
            }
        }
        return list.first
    }
    
    class func applyAuto(borrowingLoanType: Int, _ couponId: String = "", handler:@escaping NetHandler<KAApply>) {
        let paramDic: [String : Any] = [
            "userGid" : KAUserManager.shared.user.userGid,
            "productType" : 1,
            "isGetCredit" : "0",
            "pageId" : "index",
            "updateEmergencyContactList" : 0,
            "isNeedCache" : 0,
        ]
        UIViewController.ka_current().view.showLoading()
        applyProvider.request(.applyAuto(paramDic)) { result in
            UIViewController.ka_current().view.hideLoading()
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAApply>.handleResponseData(response.data) { isSuccess, message, response in
                        handler(isSuccess,message, response)
                        if !isSuccess { UIViewController.ka_current().view.makeToast(message); return }
                        guard let apply = response?.content else { return }
                        //Under review: 1  Credit failure:-1  Credit success: 2
                        if apply.basicsAuth == 1 { //审核中
                            UIViewController.ka_current().navigationController?.pushViewController(KAApplyResultVC(reviewResult: .reviewing), animated: true); return
                        }
                        if apply.basicsAuth == -1 { //审核失败
                            UIViewController.ka_current().navigationController?.pushViewController(KAApplyResultVC(reviewResult: .fail), animated: true); return
                            
                            //当天拒绝贷款
                            KAAFTool.logEvent(event: "SKP_Refusingloan_sameday")
                            
                        }
                        if apply.basicsAuth != 2 { //通过上面两个判断，这里!=2就是还没授信，去授信
                            let infoVC = KAInfoVC(model: apply)
                            UIViewController.ka_current().navigationController?.pushViewController(infoVC, animated: true); return
                        }
                        
                        //下面为apply.basicsAuth==2的情况
                        guard let json = KADBDBManager.ka_getObject(by: "homeInfo") as? String  else {return}
                        let homeInfo = json.kj.model(KAHomeInfo.self)
                        
                        //大额
                        if homeInfo?.isSubLogic == 1 {
                            //被拒绝
                            if (apply.refuseFlag == "1" || apply.refuseFlag == "3") && apply.installRefuseFlag == "1" {
                                //当天拒绝贷款
                                KAAFTool.logEvent(event: "SKP_Refusingloan_sameday")
                                
                                UIViewController.ka_current().navigationController?.pushViewController(KAApplyResultVC(reviewResult: .fail), animated: true)
                            } else {
                                self.showFlutter(borrowingLoanType: borrowingLoanType, couponId: couponId)
                            }
                        } else {
                            //小额、蝌蚪贷
                            switch apply.refuseFlag {
                                //被拒绝
                            case "1": fallthrough
                            case "3":
                                //当天拒绝贷款
                                KAAFTool.logEvent(event: "SKP_Refusingloan_sameday")
                                
                                UIViewController.ka_current().navigationController?.pushViewController(KAApplyResultVC(reviewResult: .fail), animated: true)
                                //审核中
                            case "8": fallthrough
                            case "10":
                                UIViewController.ka_current().navigationController?.pushViewController(KAApplyResultVC(reviewResult: .reviewing), animated: true)
                            default:
                                //去借款
                                self.showFlutter(borrowingLoanType: borrowingLoanType, couponId: couponId)
                            }
                        }
                        
                    }
                }else {
                    handler(false, badNetWorking, nil)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    class func showFlutter(borrowingLoanType: Int, couponId: String = "") {
        var route: String = "/loan"
        if !couponId.isEmpty {
            route = "/loan?voucherGid=\(couponId)"
        }
        KAFlutterManager.showFlutterVC(route: route, parameter: ["borrowingLoanType" : borrowingLoanType, "mobile" : KAUserManager.shared.user.mobile])
    }
}
